package com.zhao.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Slf4j
public final class SignUtil {

    public static String buildMessage(String method, String canonicalUrl, Long timestamp, String nonceStr, String body) {
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }

    public static String getToken(String method, String canonicalUrl, Long timestamp, String body, String mchId, String privateKeyStr, String nonceStr, String serialNo) throws Exception {
        timestamp = timestamp == null ? (System.currentTimeMillis() / 1000) : timestamp;
        nonceStr = StringUtils.isEmpty(nonceStr) ? UUID.randomUUID().toString() : nonceStr;
        String message = buildMessage(method, canonicalUrl, timestamp, nonceStr, body);
        log.info(message);
        String signature = RSAUtil.sign(message, RSAUtil.getPrivateKey(privateKeyStr));
        return "mchid=\"" + mchId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + serialNo + "\","
                + "signature=\"" + signature + "\"";
    }
}
